package cn.b.sky.mes.em.service.impl;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import cn.b.sky.mes.em.model.SpotInspectionAttach;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.b.sky.mes.em.dao.SpotInspectionDao;
import cn.b.sky.mes.em.model.SpotInspection;
import cn.b.sky.mes.em.model.condition.SpotInspectionCondition;
import cn.b.sky.mes.em.service.SpotInspectionService;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.common.utils.FTPUtils;
import cn.b.sky.common.utils.SkyFileUtils;
import cn.b.sky.common.utils.SpringBeanUtil;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.model.Attachment;
import cn.b.sky.user.service.AttachmentService;

@Service("spotInspectionSerive")
public class SpotInspectionServiceImpl implements SpotInspectionService {

  private static final Logger LOGGER = LoggerFactory.getLogger(SpotInspectionServiceImpl.class);

  @Resource
  SpotInspectionDao spotInspectionDao;

  @Resource
  AttachmentService attachmentService;

  @Override
  public List<SpotInspection> selectSpotInspectionListByCondition(SpotInspectionCondition condition) {
    if (condition == null) {
      condition = new SpotInspectionCondition();
    }
    if (StringUtils.isBlank(condition.getOrderField())) {
      condition.setOrderField("createDateTime");
      condition.setOrderDirection("desc");
    }
    return spotInspectionDao.selectSpotInspectionListByCondition(condition);
  }

  @Override
  public int selectSpotInspectionCountByCondition(SpotInspectionCondition condition) {
    if (condition == null) {
      condition = new SpotInspectionCondition();
    }
    return spotInspectionDao.selectSpotInspectionCountByCondition(condition);
  }

  @Override
  public SpotInspection getSpotInspection(Long id) {
    if (id == null) {
      return null;
    }
    return spotInspectionDao.getSpotInspection(id);
  }

  @Override
  public boolean insertSpotInspection(SpotInspection inspection) {
    if (StringUtils.isBlank(inspection.getEquipmentCode())) {
      return false;
    }
    spotInspectionDao.insertSpotInspection(inspection);
    return true;
  }

  @Override
  public boolean updateSpotInspection(SpotInspection inspection) {
    if (inspection.getId() == null) {
      return false;
    }

    spotInspectionDao.updateSpotInspection(inspection);
    return true;
  }

  @Override
  public BatchJobReport deleteSpotInspection(Long id, String siteCode) {
    if (id != null) {
      String message = "";
      String cause = "";
      boolean success = true;
      try {
        SpotInspection inspection = spotInspectionDao.getSpotInspection(id);
        if (!StringUtils.isBlank(inspection.getAttachmentCode())) {
          deleteAttachment(siteCode, inspection.getAttachmentCode());
        }
        spotInspectionDao.deleteSpotInspection(id);
      } catch (Exception e) {
        LOGGER.error("{}", e);
        success = false;
        String errorMsg = e.getMessage();
        if (DatabaseUtils.isConstraintsError(e.getMessage())) {
          //外键删除已存在提示
          errorMsg = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
              SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
              + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                  SecurityContextUtil.getLanguageCode(), "notDelete.M");
        }
        cause = errorMsg;
      }
      return new BatchJobReport(message, cause, success);
    } else {
      return new BatchJobReport("", "equipment is null", false);
    }
  }

  @Override
  public void insertSpotInspectionAndAttach(SpotInspection inspection, SpotInspectionAttach attach, MultipartFile file,
                                            String siteCode) {
    //插入系统附件表
    this.insertAttach(attach, file, siteCode);
    inspection.setAttachmentCode(attach.getAttachmentCode());
    //插入点检表
    this.insertSpotInspection(inspection);
  }

  @Override
  public void updateSpotInspectionAndAttach(SpotInspection inspection, SpotInspectionAttach attach, MultipartFile file,
      String siteCode) {
    //插入系统附件表
    this.insertAttach(attach, file, siteCode);
    inspection.setAttachmentCode(attach.getAttachmentCode());
    //更新点检表
    this.updateSpotInspection(inspection);

  }

  private void insertAttach(SpotInspectionAttach attach, MultipartFile file, String siteCode) {
    String saveName = UUID.randomUUID().toString();
    String filePath = SkyFileUtils.buildFilePath("spotInspection");
    String fileName = file.getOriginalFilename();
    Long size = file.getSize();
    String md5 = "";
    try {
      md5 = SkyFileUtils.getMD5String(file.getBytes());
    } catch (IOException e) {
      LOGGER.error("{}", e);
    }
    Attachment att = attachmentService.selectAttachmentByHashCode(siteCode, md5);
    if (att != null) {
      att.setRefCount(att.getRefCount() + 1);
      attachmentService.updateAttachmentRefCount(att);
      attach.setAttachmentCode(att.getAttachmentCode());
    } else {
      String newFileName = SkyFileUtils.renameFileName(fileName, saveName);
      FTPUtils ftpUtils = (FTPUtils) SpringBeanUtil.getBean("ftpUtils");
      String savePath = ftpUtils.uploadMultipartFiles(file, filePath, newFileName);
      Attachment atachment = new Attachment();
      atachment.setSiteCode(siteCode);
      atachment.setAttachmentCode(saveName);
      atachment.setSavePath(savePath);
      atachment.setFileName(fileName);
      atachment.setFileSize(size);
      atachment.setHashCode(md5);
      atachment.setRefCount(1);
      attachmentService.insertAttachment(atachment);
      attach.setAttachmentCode(saveName);
    }

  }

  @Override
  public void deleteAttachment(String siteCode, String attachmentCode) {
    attachmentService.deleteAttachment(siteCode, attachmentCode);
  }

}
